package com.example.grpcserver.service;

import com.example.grpcserver.entity.AccountEntity;
import com.example.grpcserver.exception.NotFoundException;
import com.example.grpcserver.repository.AccountRepository;
import io.grpc.stub.StreamObserver;
import java.util.Optional;
import net.devh.boot.grpc.server.service.GrpcService;
import org.example.grpcserver.Account;
import org.example.grpcserver.AccountServiceGrpc;
import org.example.grpcserver.IdQuery;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Create on: 2020/8/18.
 *
 * @author hongwei.zhang
 */
@GrpcService
public class AccountGrpcService extends AccountServiceGrpc.AccountServiceImplBase{
  private AccountRepository accountRepository;

  @Autowired
  public AccountGrpcService(AccountRepository accountRepository) {
    this.accountRepository = accountRepository;
  }

  @Override
  public void getOne(IdQuery request, StreamObserver<Account> responseObserver) {
    Optional<AccountEntity> opt = accountRepository.findById(request.getId());
    if (opt.isPresent()) {
      AccountEntity accountEntity = opt.get();
      Account response = Account.newBuilder().setId(accountEntity.getId()).setEmail(accountEntity.getEmail()).build();
      responseObserver.onNext(response);
    } else {
      responseObserver.onError(new NotFoundException());
    }
    responseObserver.onCompleted();
  }

  //todo

}
